<template>
  <Form ref="formCom" class="xtx-form" :validation-schema="schema" v-slot='{errors}' >
    {{form}}
    <div class="user-info">
      <img :src="avatar" alt="" />
      <p>Hi，{{nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field v-model="form.mobile" name="mobile" :class="{err:errors.mobile}" class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <div v-if="errors.mobile" class="error">{{errors.mobile}}</div>
      <div class="error"></div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field v-model="form.code" name="code" :class="{err:errors.code}" class="input" type="text" placeholder="短信验证码" />
        <span @click="send()" class="code">
          {{time===0?'发送验证码':`${time}秒后发送`}}
        </span>
      </div>
      <div v-if="errors.code" class="error">{{errors.code}}</div>
      <div class="error"></div>
    </div>
    <a href="javascript:;" @click="submit" class="submit">立即绑定</a>
  </Form>
</template>

<script>
import { reactive, ref } from 'vue'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/vee-validate-schema'
import { Message } from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/shared'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  components: { Form, Field },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // 获取QQ头像和昵称
    const nickname = ref('')
    const avatar = ref('')
    if (QC.Login.check()) {
      QC.api('get_user_info').success(({ data }) => {
        // console.log(data)
        nickname.value = data.nickname
        avatar.value = data.figureurl_2
      })
    }
    // 2. 完成表单校验
    // 3. 收集表单信息
    const form = reactive({
      mobile: '',
      code: ''
    })
    // 4. 发送验证码

    // 定时器
    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })
    // 4.1 绑定发送验证码按钮点击事件
    // 4.2 校验手机号，如果成功才去发送短信（定义API），请求成功开启60s的倒计时，不能再次点击，倒计时结束恢复
    // 4.3 如果失败，失败的校验样式显示出来
    const formCom = ref(null)
    const send = async () => {
      const valid = schema.mobile(form.mobile)
      if (valid === true) {
        // 通过
        if (time.value === 0) {
        // 没有倒计时才可以发送
          await userQQBindCode(form.mobile)
          Message({ type: 'success', message: '发送成功' })
          time.value = 60
          resume()
        }
      } else {
        // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
        formCom.value.setFieldError('mobile', valid)
      }
    }
    // 5. 提交绑定
    const store = useStore()
    const router = useRouter()
    const submit = async () => {
      // Form组件提供了一个 validate 函数作为整体表单校验，当是返回的是一个promise
      const valid = await formCom.value.validate()
      // console.log(valid)
      if (!valid) return Message({ type: 'error', message: '表单验证失败' })
      try {
        const { result } = await userQQBindLogin({ unionId: props.unionId, ...form })
        // 实现和之前登录一样的逻辑
        // 1. 存储用户信息
        store.commit('user/setUser', result)
        // 2. 跳转到来源页或者首页
        router.push(router.currentRoute.value.query.redirectUrl || '/')
        // 3. 成功提示
        Message({ type: 'success', message: 'QQ绑定成功' })
        // 登录成功后合并购物车数据
        store.dispatch('cart/mergeLocalCart')
      } catch (error) {
        Message({ type: 'error', message: error.response.data.message || '完善信息失败' })
      }
    }

    return { nickname, avatar, form, schema, send, time, formCom, submit }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
